<?php

namespace plugins\logistics\controller;

use cmf\controller\PluginBaseController; //引用插件基类
use cmf\controller\PluginRestBaseController;
use plugins\logistics\model\LogisticsKdniaoModel;
use think\Db;
use think\Model;

class ApiIndexController extends PluginBaseController
{
    private  $KdApi = '';
    public function _initialize()
    {
        $dir =  dirname(__FILE__);
        $file=scandir($dir); 
        unset($file[0],$file[1]);//因为这样获取到的数组前两位是. 和..,所以删去
        foreach($file as $key =>$value)
        {
            $filename ='';
            if($value === 'ApiIndexController.php') continue;//跳出本次循环
            if(substr($value,0,3)=== 'Api')
            {
                $filename = $value; 
                break;//终止循环
            }
        }
        if(!empty($filename))
        {
            $filename = str_replace(strrchr($filename, "."),"",$filename);
            $res = '\\plugins\logistics\controller\\'.$filename; 
            
            $this->API = new $res();
        }
        $this->KdApi = new LogisticsKdniaoModel;
        // else{ echo 'false'; }
         
    }


    /**
     * 查询物流
     * @param  $isModule
     * @param  $ShipperCode   快递公司编码
     * @param  $LogisticCode  物流单号
     * @param  $store  店铺id
     * @return void|\返回json字符串
     */
    public function query($ShipperCode='',$LogisticCode='',$store='',$CustomerName='')
    {
        $order_num = $this->request->post('order_num');
        if(empty($order_num)){
            return api_json_echo(false,'系统数据错误','',1000);
        }
        $data = db('logistics_order')->where('order_num',$order_num)->find();
        if(empty($data)){
            return api_json_echo(false,'系统数据错误','',1000);
        }

        $CustomerName = substr($data['mobile'],-4);
        $ShipperCode = $data['code'];
        $LogisticCode = $data['logistics_code'];

        if(empty($LogisticCode)) return api_json_echo(true,'暂无物流信息');


        $where = ['ShipperCode'=>$ShipperCode,'LogisticCode'=>$LogisticCode];
        $logistics = db('logistics_record')->where($where)->find();
        if($logistics){//有记录
            $time = intval( (time()-$logistics['add_time'] )/3600);//相差时间
            if($logistics['State']==3 || $time<2){//物流已签收或两小时内更新过
                $msg = json_decode($logistics['logistics'],true);
                return api_json_echo(true,'获取成功',$msg);
            }
        }

        $EXinfo = db('logistics_confign')->where('store_id','admin')->find();
        $res = $this->KdApi->getOrderTracesByJson($ShipperCode,$LogisticCode,$EXinfo,$CustomerName);

        $msg = json_decode($res,true);
        if($msg['Success']==true){
            $time = time();
            db('logistics_record')->insert(['ShipperCode'=>$ShipperCode,'LogisticCode'=>$LogisticCode,'logistics'=>$res,'add_time'=>$time,'State'=>$msg['State']]);//保存物流信息
        }
        if($msg['Success']==true){

            $code = Db::name('logistics')->where('code',$msg['ShipperCode'])->find();
            $msg['company']=$code['company'];

            //按照时间排序
            if ($msg['State'] != 0) {
                $ctime_str = array();
                foreach($msg['Traces'] as $key=>$v){
                    $msg['Traces'][$key]['AcceptTime'] = strtotime($v['AcceptTime']);
                    $ctime_str[] = $msg['Traces'][$key]['AcceptTime'];
                }
                array_multisort($ctime_str,SORT_DESC,$msg['Traces']);
                foreach ($msg['Traces'] as $key => $value) {
                    $value['AcceptTime'] = date('Y-m-d H:i:s',$value['AcceptTime']);
                    $msg['Traces'][$key] = $value;
                }
            }
            /*
            物 流 状 态 ：
            0-无 轨 迹
            1-已揽收
            2-在途中
            3-签收 */
            if($msg['State']=='0'){
                $msg['State']='无轨迹';
            }else if($msg['State']=='1'){
                $msg['State']='已揽收';
            }else if($msg['State']=='2'){
                $msg['State']='在途中';
            }else if($msg['State']=='3'){
                $msg['State']='签收';
            }

        }
        return api_json_echo(true,'获取成功',$msg);
    }



}